package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TrafficPageViewBean;
import com.atguigu.func.MyWindowFunction;
import com.atguigu.uitl.ClickHouseUtil;
import com.atguigu.uitl.DateFormatUtil;
import com.atguigu.uitl.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.planner.expressions.DateFormat;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/17 15:53
 */
public class Dws02_TrafficVcChArIsNewPageViewWindow {
    public static void main(String[] args) throws Exception {
        // todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从页面主题读取数据(dwd_traffic_page_log)
        String topic="dwd_traffic_page_log";
        String groupId="vc_ch_ar_isNew_page_view_0926";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //todo 3 数据转为JSONObj对象并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWmDS = kafkaDS.map(JSONObject::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("ts");
                            }
                        })));
        //todo 4 按照mid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWmDS.keyBy(value -> value.getJSONObject("common").getString("mid"));
        //todo 5 转为javaBean对象
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TrafficPageViewBean>() {
            private ValueState<String> lastVisitDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlCfg = StateTtlConfig
                        .newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_visit_dt", String.class);
                valueStateDescriptor.enableTimeToLive(ttlCfg);
                lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TrafficPageViewBean> out) throws Exception {
                //拿到上次日期和当前日期
                String lastDt = lastVisitDt.value();
                Long ts = value.getLong("ts");
                String curtDt = DateFormatUtil.toDate(ts);
                JSONObject page = value.getJSONObject("page");
                String lastPageId = page.getString("last_page_id");
                Long sv = 0L;
                Long uv = 0L;
                if (lastPageId == null) {
                    sv = 1L;
                }
                if (lastDt == null || !lastDt.equals(curtDt)) {
                    uv = 1L;
                    lastVisitDt.update(curtDt);
                }
                JSONObject common = value.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                out.collect(new TrafficPageViewBean("",
                        "",
                        vc,
                        ch,
                        ar,
                        is_new,
                        uv,
                        sv,
                        1L,
                        page.getLong("during_time"),
                        null
                ));
            }
        });
        //todo 6 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultDS = trafficPageViewBeanDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        return value1;
                    }
                }, new AllWindowFunction<TrafficPageViewBean, TrafficPageViewBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TrafficPageViewBean> values, Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavaBeanField(next, window));
                    }
                });
        //todo 7 写出数据到clickhouse
        resultDS.print("result>>>>>>>>>>>>.");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into  dws_traffic_vc_ch_ar_is_new_page_view_window values(?,?,?,?,?,?,?,?,?,?,?)"));
        //todo 8 启动
        env.execute();

    }
}
